package com.skyline.common.util;

import java.util.regex.Pattern;

/**
 * StringUtil is an util class of String
 * 
 * @author Jairus Chan
 * @version 0.1
 * */
@Deprecated
public class HtmlUtils {
	private static java.util.regex.Pattern p_script;
	private static java.util.regex.Matcher m_script;
	private static java.util.regex.Pattern p_style;
	private static java.util.regex.Matcher m_style;
	private static java.util.regex.Pattern p_html;
	private static java.util.regex.Matcher m_html;

	private static String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
	private static String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
	private static String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

	/**
	 * Html2Text is used to clean the HTML tags in a String which is very useful
	 * in the article component and so on
	 * 
	 * @param inputString
	 *            the String which is needed to clean
	 * @return String,the result of cleaning operation
	 */
	public static String html2text(String inputString) {
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";

		try {
			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签

			textStr = htmlStr;

		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}
		return textStr;// 返回文本字符串
	}
	
	public String replace(String strSource, String strOriginal, String strNew) {
		if (strSource == null)
			return null;
		StringBuffer output = new StringBuffer();
		int lengOfsource = strSource.length();
		int lengOfold = strOriginal.length();
		int posStart = 0;
		int pos;

		while ((pos = strSource.indexOf(strOriginal, posStart)) >= 0) {

			output.append(strSource.substring(posStart, pos));
			output.append(strNew);
			posStart = pos + lengOfold;
		}
		if (posStart < lengOfsource) {
			output.append(strSource.substring(posStart));
		}
		return output.toString();
	}

	public String toHtml(String s) {
		s = replace(s, "<", "&lt;");
		s = replace(s, ">", "&gt;");
		s = replace(s, "&", "&amp;");
		s = replace(s, "\t", " ");
		s = replace(s, "\r\n", "\n");
		s = replace(s, "\n", "<br>");
		s = replace(s, " ", "&nbsp;");
		s = replace(s, "'", "&#39;");
		s = replace(s, "\\", "&#92;");
		return s;
	}
}
